package hui.zhang.web.action.take_delivery;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;

import hui.zhang.domain.take_delivery.WayBill;
import hui.zhang.service.take_delivery.WayBillService;
import hui.zhang.utils.BaseAction;

/**
 * 运单管理
 * 
 * @author hui.zhang
 * @date 2017年12月26日 下午6:48:47
 */

@ParentPackage("struts-default")
@Namespace("/")
@Controller
@Scope("prototype")
@SuppressWarnings("all")
public class WayBillAction extends BaseAction<WayBill> {

	@Autowired
	private WayBillService wayBillService;

	// 加入日志
	private static final Logger LOGGER = Logger.getLogger(WayBillAction.class);

	@Action(value = "waybill_save")
	public String save() {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 去除没有id的order对象
			if (model.getOrder() != null && (model.getOrder().getId() == null || model.getOrder().getId() == 0)) {
				model.setOrder(null);
			}
			wayBillService.save(model);
			// 保存成功
			result.put("success", true);
			result.put("msg", "保存运单成功！");
			LOGGER.info("保存运单成功！运单号：" + model.getWayBillNum());
		} catch (Exception e) {
			// 保存失败
			result.put("success", false);
			result.put("msg", "运单保存失败！");
			LOGGER.error("保存运单失败！运单号：" + model.getWayBillNum(), e);
		}
		toJsonAndResponse(result);
		return NONE;
	}

	@Action(value = "waybill_pageQuery")
	public String findByPage() {
		// 无条件查询
		Pageable pageable = new PageRequest(page - 1, rows, new Sort(new Order(Direction.DESC, "id")));

		// 调用业务层
		Page<WayBill> pageData = wayBillService.findByPage(model, pageable);
		toJsonAndResponse(pageData);
		return NONE;
	}

	@Action(value = "waybill_findByWayBillNum")
	public String findByWayBillNum() {
		WayBill wayBill = wayBillService.findByWayBillNum(model.getWayBillNum());
		Map<String, Object> map = new HashMap<String, Object>();
		if (wayBill == null) {
			map.put("success", false);
		} else {
			map.put("success", true);
			map.put("wayBillData", wayBill);
		}
		toJsonAndResponse(map);
		return NONE;
	}

}
